<template>
  <el-container>
    <el-main>

      <el-button-group style="margin-bottom: 5px;">
        <el-button v-if="editing" size="small" icon="el-icon-check" @click="handleClickSave" type="primary"></el-button>
        <el-button v-if="editing" size="small" icon="el-icon-back" @click="handleClickBack"></el-button>
        <el-button v-else size="small" icon="el-icon-back" @click="handleClickBack" type="primary"></el-button>
      </el-button-group>

      <el-collapse v-model="activeNames">
        <el-collapse-item title="实体" name="1">

          <el-form style="width: 460px;" :model="entity"
            label-width="100px" label-position="left"  size="small">
            <el-form-item label="实体编码" prop="entityPoName">
              <el-input size="small" :disable="pageState === 'view'" v-model="entity.entityCode"></el-input>
            </el-form-item>
            <el-form-item label="实体名称" prop="entityName">
              <el-input size="small" :disable="pageState === 'view'" v-model="entity.entityName"></el-input>
            </el-form-item>
            <el-form-item label="实体描述" prop="entityDesc">
              <el-input size="small" :disable="pageState === 'view'" v-model="entity.entityDesc"></el-input>
            </el-form-item>
          </el-form>
        </el-collapse-item>
        <el-collapse-item title="实体字段" name="2">

          <el-button-group style="margin-bottom: 5px;">
            <el-button v-if="editing" size="small" :disabled="!attributeAddEnable" @click="handleAttributeAdd" icon="el-icon-plus"></el-button>
            <el-button v-if="editing" size="small" :disabled="!attributeDeleteEnable" @click="handleAttributeDelete" icon="el-icon-delete"></el-button>
            <el-button v-if="editing" size="small" :disabled="!attributeUpwardsEnable" @click="handleAttributeUpwards" icon="el-icon-arrow-up"></el-button>
            <el-button v-if="editing" size="small" :disabled="!attributeDownwardsEnable" @click="handleAttributeDownwards" icon="el-icon-arrow-down"></el-button>
            <el-button v-if="editing" size="small" :disabled="!attributeAddTemplateEnable" @click="handleAttributeAddTemplate" icon="el-icon-printer"></el-button>
          </el-button-group>
          <el-table
            size="small"
            ref="attributesTable"
            style="width: 100%;"
            :data="attributes"
            :cell-style="cellStyle"
            @selection-change="handleSelectionChange">
            <el-table-column
              type="selection"
              :reserve-selection="true"
              width="55">
            </el-table-column>
            <el-table-column
              label="实体字段编号"
              width="180">
              <template slot-scope="scope">
                <el-input size="small" v-model="scope.row.entityAttributeCode"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="实体字段名称"
              width="200">
              <template slot-scope="scope">
                <el-input size="small" v-model="scope.row.entityAttributeName"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              label="字段数据类型"
              width="220">
              <template slot-scope="scope">
                <el-select size="small" 
                  v-model="scope.row.entityAttributeValueType" 
                  placeholder="请选择"
                  @change="entityAttributeValueTypeChange($event, scope.row)">
                  <el-option
                    v-for="item in entityAttributeValueTypeOptions"
                    :key="item.index"
                    :label="item.text"
                    :value="item.index">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column
              label="不区分大小写"
              width="120">
              <template slot-scope="scope">
                <el-checkbox size="small" :disabled="!scope.row._ci_enable" v-model="scope.row.entityAttributeValueCi"></el-checkbox>
              </template>
            </el-table-column>

            <el-table-column
              label="固定长度"
              width="80">
              <template slot-scope="scope">
                <el-checkbox size="small" :disabled="!scope.row._lf_enable" v-model="scope.row.entityAttributeValueLengthFixed"></el-checkbox>
              </template>
            </el-table-column>

            <el-table-column
              label="总长度"
              width="100">
              <template slot-scope="scope">
                <el-input size="small" :disabled="!scope.row._len_enable" v-model="scope.row.entityAttributeValueLength1"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              label="小数长度"
              width="100">
              <template slot-scope="scope">
                <el-input size="small" :disabled="!scope.row._decimal_len_enable" v-model="scope.row.entityAttributeValueLength2"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              label="实体字段描述">
              <template slot-scope="scope">
                <el-input size="small" v-model="scope.row.entityAttributeDesc"></el-input>
              </template>
            </el-table-column>

          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-main>
  </el-container>
</template>
<script>
import { EntityAttributeValueType } from "@/data/dic.js";
  export default {
    
    data() {
      return {
        // 卡片展开状况，无需关注
        activeNames: ['1', '2'],
        // 页面状态
        // 目前有三种状态："add"， "edit", "view"
        pageState: "view",
        // 主体模型
        entity: {
          entityId: null,
          entityCode: "",
          entityName: "",
          entityDesc: "",
          attributes: []
        },
        // 列表数据
        attributes: [],
        // 被选中的列表数据
        selectedAttributes: [],
        // 属性值类型选项
        entityAttributeValueTypeOptions: []
      };
    },
    mounted() {
      let me = this;
      // 获取字典
      me.$http.post("/common/list/enum").then((res) => {
        me.entityAttributeValueTypeOptions = res.data.data["ENTITYATTRIBUTEVALUETYPE"];
      });
      // 依据页面状态 二次渲染
      me.pageState = me.$route.query.type;
      if(me.pageState === "view" || me.pageState === "edit") {
        let entityId = me.$route.query.entityId;

        me.$http
          .post("/uni/get", {
            modelName: "entity",
            modelId: entityId
          })
          .then((res) => {
            me.entity = res.data.data;
            me.attributes = res.data.data.attributes;
            for(let i = 0; i < me.attributes.length; i++) {
              me.setControlStatus(me.attributes[i]);
            }
          });
      }
    },
    computed: {
      editing: function() {
        return this.pageState === "add" || this.pageState === "edit";
      },
      attributeAddEnable: function() {
        return this.selectedAttributes.length === 0;
      },
      attributeDeleteEnable: function() {
        return this.selectedAttributes.length > 0;
      },
      attributeUpwardsEnable: function() {
        let enable = false;
        if(this.selectedAttributes.length > 0 && this.attributes.length > 1) {
          let selectLen = this.selectedAttributes.length;
          let len = this.attributes.length;
          if(selectLen == 1) {
            if(this.attributes.indexOf(this.selectedAttributes[0]) > 0) {
              return true;
            }
          } else {
            var first = -1, last = -1, count = 0;
            for(let i = 0; i < len; i++) {
              if(this.selectedAttributes.indexOf(this.attributes[i]) > -1) {
                if(count == 0) {
                  first = i;
                }
                last = i;
                count++;
              }
            }
            if(count > 0 && count == last - first + 1 && first > 0) {
              return true;
            }
          }
        }
        return enable;
      },
      attributeDownwardsEnable: function() {
        let enable = false;
        if(this.selectedAttributes.length > 0 && this.attributes.length > 1) {
          let selectLen = this.selectedAttributes.length;
          let len = this.attributes.length;
          if(selectLen == 1) {
            if(this.attributes.indexOf(this.selectedAttributes[0]) < len - 1) {
              return true;
            }
          } else {
            var first = -1, last = -1, count = 0;
            for(let i = 0; i < len; i++) {
              if(this.selectedAttributes.indexOf(this.attributes[i]) > -1) {
                if(count == 0) {
                  first = i;
                }
                last = i;
                count++;
              }
            }
            if(count > 0 && count == last - first + 1 && last < len - 1) {
              return true;
            }
          }
        }
        return enable;
      },
      attributeAddTemplateEnable: function() {
        return this.selectedAttributes.length === 0 && this.entity.entityCode && this.entity.entityName;
      },

    },
    methods: {
      cellStyle({row, column, rowIndex, columnIndex}) {
        return ""; //"padding: 2px 0;"
      },
      handleSelectionChange(val) {
        this.selectedAttributes = val;
      },
      handleClickBack() {
        window.history.length > 1
                ? this.$router.go(-1)
                : this.$router.push("/");
      },
      handleClickSave() {
        var url = "";
        if(this.pageState == "add") {
          url = "/uni/save";
        } else if(this.pageState == "edit") {
          url = "/uni/update";
        }
        if(url === "") {
          console.error("entity form page state is out of control");
          return;
        }
        let me = this;
        let ok = (res) => {
          me.entity = res.data.data;
          me.attributes = res.data.data.attributes;
          for(let i = 0; i < me.attributes.length; i++) {
            me.setControlStatus(me.attributes[i]);
          }
          me.pageState = "view";
        };
        let err = (error) => {
          console.log(error);
        };
        me.entity.attributes = me.attributes;
        this.$http
          .post(url, {
              modelName: "entity",
              "model": me.entity
          })
          .then(ok)
          .catch(err);
      },
      generateOptions(max, hasEmptyOption) {
        let options = [];
        if(hasEmptyOption) {
          options.push[{index: null, text: "请选择"}];
        }
        for(let i = 1; i <= max; i++) {
          options.push[{index: i, text: i}];
        }
        return options;
      },
      handleAttributeAddTemplate() {
        this.handleAttributeAdd({
          entityAttributeValueType: EntityAttributeValueType.NUMBER_INT_8,
          entityAttributeCode: this.entity.entityCode + "Id",
          entityAttributeName: this.entity.entityName + "主键"
        });
        this.handleAttributeAdd({
          entityAttributeValueType: EntityAttributeValueType.STRING,
          entityAttributeCode: this.entity.entityCode + "Code",
          entityAttributeName: this.entity.entityName + "编号"
        });
        this.handleAttributeAdd({
          entityAttributeValueType: EntityAttributeValueType.STRING,
          entityAttributeCode: this.entity.entityCode + "Name",
          entityAttributeName: this.entity.entityName + "名称"
        });
      },
      handleAttributeAdd(row) {
        row = row && row.entityAttributeValueType ? row : {
          entityAttributeValueType: EntityAttributeValueType.STRING
        };
        this.setControlStatusAndValue(row);
        this.attributes.push(row);
        this.positionChange();
      },
      setControlStatus(row) {

        // 组件值和状态重置表                                        大小写敏感  定长        总长         小数部分长度
        let cvsTable = [];
        cvsTable[EntityAttributeValueType.STRING]                 = [true,       true,       true,        false];
        cvsTable[EntityAttributeValueType.NUMBER_INT_4]           = [false,      false,      false,       false];
        cvsTable[EntityAttributeValueType.NUMBER_INT_8]           = [false,      false,      false,       false];
        cvsTable[EntityAttributeValueType.NUMBER_FLOAT_4]         = [false,      false,      false,       false];
        cvsTable[EntityAttributeValueType.NUMBER_FLOAT_8]         = [false,      false,      false,       false];
        cvsTable[EntityAttributeValueType.NUMBER_DECIMAL]         = [false,      false,      true,        true];
        cvsTable[EntityAttributeValueType.BOOLEAN]                = [false,      false,      false,       false];

        // 大小写敏感
        row._ci_enable                                            = cvsTable[row.entityAttributeValueType][0];
        // 固定长度
        row._lf_enable                                            = cvsTable[row.entityAttributeValueType][1];
        // 总长
        row._len_enable                                           = cvsTable[row.entityAttributeValueType][2];
        // 小数部分长度
        row._decimal_len_enable                                   = cvsTable[row.entityAttributeValueType][3];
        return row;
      },
      setControlValue(row) {

        // 组件值和状态重置表                                        大小写敏感  定长      总长     小数部分长度
        let cvsTable = [];
        cvsTable[EntityAttributeValueType.STRING]                 = [false,      false,    255,     null];
        cvsTable[EntityAttributeValueType.NUMBER_INT_4]           = [null,       null,     null,    null];
        cvsTable[EntityAttributeValueType.NUMBER_INT_8]           = [null,       null,     null,    null];
        cvsTable[EntityAttributeValueType.NUMBER_FLOAT_4]         = [null,       null,     null,    null];
        cvsTable[EntityAttributeValueType.NUMBER_FLOAT_8]         = [null,       null,     null,    null];
        cvsTable[EntityAttributeValueType.NUMBER_DECIMAL]         = [null,       null,     16,      6];
        cvsTable[EntityAttributeValueType.BOOLEAN]                = [null,       null,     null,    null];

        // 大小写敏感
        row.entityAttributeValueCi                                = cvsTable[row.entityAttributeValueType][0];
        // 固定长度
        row.entityAttributeValueLengthFixed                       = cvsTable[row.entityAttributeValueType][1];
        // 总长
        row.entityAttributeValueLength1                           = cvsTable[row.entityAttributeValueType][2];
        // 小数部分长度
        row.entityAttributeValueLength2                           = cvsTable[row.entityAttributeValueType][3];
        return row;
      },
      setControlStatusAndValue(row) {
        this.setControlStatus(row);
        this.setControlValue(row);
      },


      handleAttributeDelete() {
        let survivors = [];
        for(let i = 0, len = this.attributes.length; i < len; i++) {
          if(this.selectedAttributes.indexOf(this.attributes[i]) < 0) {
            survivors.push(this.attributes[i]);
          }
        }
        this.$refs.attributesTable.clearSelection();
        this.attributes = survivors;
        this.positionChange();
      },
      handleAttributeUpwards() {
        let start = [], middle = [], end = [];
        let selectLength = this.selectedAttributes.length;
        let selectStart = this.attributes.indexOf(this.selectedAttributes[0]);
        start = this.attributes.slice(0, selectStart);
        middle = this.attributes.slice(selectStart, selectStart + selectLength);
        end = this.attributes.slice(selectStart + selectLength, this.attributes.length);
        end.unshift(start.pop());
        
        this.attributes = start.concat(middle, end);

        let me = this;
        setTimeout(function() {
          me.toggleRowSelection(middle[0]);
          me.positionChange();
        }, 200);
      },
      handleAttributeDownwards() {
        let start = [], middle = [], end = [];
        let selectLength = this.selectedAttributes.length;
        let selectStart = this.attributes.indexOf(this.selectedAttributes[0]);
        start = this.attributes.slice(0, selectStart);
        middle = this.attributes.slice(selectStart, selectStart + selectLength);
        end = this.attributes.slice(selectStart + selectLength, this.attributes.length);
        start.push(end.shift())
        this.attributes = start.concat(middle, end);

        let me = this;
        setTimeout(function() {
          me.selectedAttributes = middle;
          me.positionChange();
        }, 200);
      },
      positionChange() {
        let len = this.attributes.length;
        for(let i = 0; i < len; i++) {
          this.attributes[i].sq = i + 1;
        }
      },
      entityAttributeValueTypeChange(value, row) {
        this.setControlStatusAndValue(row);
      }
    }
  }
</script>

<style lang="less" scoped>

  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }

  .el-table .cell {
    padding: 0px;
  }
</style>